<template>
  <div class="category">
    <h1>{{id?'编辑':"新增"}}物品</h1>
    <el-form label-width="120px" @submit.native.prevent="save">
      <el-form-item label="名称:">
        <el-input v-model="form.name"></el-input>
      </el-form-item>

      <el-form-item label="图标:">
        <el-upload class="avatar-uploader" :action="uploadUrl" :headers="getAuthHeads()" :show-file-list="false" :on-success="afterupload">
          <img v-if="form.icon" :src="form.icon" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import http from "../axios/index.js";
export default {
  props: {
    id: String,
  },
  data() {
    return {
      form: {},
      parents: [],
    };
  },
  created() {
    this.id && this.fetch();
    this.fetchParent();
  },
  methods: {
    // 图片上传之后
    afterupload(res) {
      this.$set(this.form, "icon", res.url);
      // this.form.icon = res.url;
    },
    // 获取
    async fetch() {
      const res = await this.$http.get(`/rest/goods/${this.id}`);
      this.form = res.data;
    },
    async fetchParent() {
      const res = await this.$http.get(`/rest/goods`);
      this.parents = res.data;
    },
    async save() {
      let res;
      if (this.id) {
        res = await this.$http.put(`/rest/goods/${this.id}`, this.form);
      } else {
        res = await this.$http.post("/rest/goods", this.form);
      }
      const { data } = res;
      if (data.code == 200) {
        this.$message.success(data.msg);
        this.$router.push("/goods/list");
      }
    },
  },
};
</script>
